<?php
namespace backend\controllers;

use backend\models\RoleForm;
use yii\data\ArrayDataProvider;
use Yii;
use yii\filters\VerbFilter;
use yii\rbac\Role;
use yii\web\NotFoundHttpException;

class RoleController extends BaseController
{
    /**
     * @return array
     */
    public function behaviors()
    {
        return array_merge(parent::behaviors(),
        [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ]);
    }

    /**
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        $roles = Yii::$app->authManager->getRoles();

        return $this->render('index', [
            'dataProvider' => new ArrayDataProvider(['models' => $roles])
        ]);
    }

    /**
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new RoleForm();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', '角色创建成功。');
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * @param $name
     * @return string|\yii\web\Response
     */
    public function actionUpdate($name)
    {
        $model = new RoleForm($this->loadModel($name));
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', '角色更新成功。');
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * @param $name
     * @return \yii\web\Response
     */
    public function actionDelete($name)
    {
        $role = $this->loadModel($name);
        Yii::$app->authManager->remove($role)
        &&
        Yii::$app->session->setFlash('success', '角色删除成功。');
        return $this->redirect(['index']);
    }

    /**
     * @param $name
     * @return Role
     * @throws \yii\web\NotFoundHttpException
     */
    public function loadModel($name)
    {
        if (!$role = Yii::$app->authManager->getRole($name)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } else {
            return $role;
        }
    }
} 